﻿using Iot.Device.CharacterLcd;
using Iot.Device.Ili9341;
using Iot.Device.Pcx857x;
using IotDeviceToolHepler.Model.device;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Device.Gpio;
using System.Device.I2c;
using System.Device.Spi;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IotDeviceToolHepler.Device
{
    /// <summary>
    /// 显示设备Lcd2004显示屏Pcf8574驱动芯片
    /// </summary>
    public class DeviceDisplay_Lcd2004
    {
        /// <summary>
        /// 测试用
        /// </summary>
        public void Test()
        {
            while (true)
            {
                List<ModelWriteLcd2004> modelWriteLcd2004s = new List<ModelWriteLcd2004>();
                ModelWriteLcd2004 modelWriteLcd2004 = new ModelWriteLcd2004();
                modelWriteLcd2004.content = DateTime.Now.ToString("MM-dd HH:mm:ss");
                modelWriteLcd2004.row = 0;
                modelWriteLcd2004.left = 1;
                modelWriteLcd2004s.Add(modelWriteLcd2004);
                Lcd2004(3, modelWriteLcd2004s);
                Thread.Sleep(1000);
            }
        }

        /// <summary>
        /// 基于Pcf8574 Lcd2004显示屏i2c  方式 适配树莓派 busId=1、香橙派 busId=3
        /// </summary>
        /// <param name="busId">总线Id</param>
        /// <param name="content">内容</param>
        /// <param name="left">共16列，第几列显示</param>
        /// <param name="line">共2行，在第几行显示</param>
        public void Lcd2004(int busId, List<ModelWriteLcd2004> ModelWriteLcd2004s)
        {

            Console.WriteLine("Displaying current time. Press Ctrl+C to end.");
            using I2cDevice i2c = I2cDevice.Create(new I2cConnectionSettings(busId, 0x27));
            using var driver = new Pcf8574(i2c);
            using var lcd = new Lcd2004(registerSelectPin: 0,
                                    enablePin: 2,
                                    dataPins: new int[] { 4, 5, 6, 7 },
                                    backlightPin: 3,
                                    backlightBrightness: 0.1f,
                                    readWritePin: 1,
                                    controller: new GpioController(PinNumberingScheme.Logical, driver));
            lcd.Clear();
            foreach (ModelWriteLcd2004 item in ModelWriteLcd2004s)
            {
                lcd.SetCursorPosition(item.left, item.row);
                lcd.Write(item.content);
            }
            //代码来源https://learn.microsoft.com/zh-cn/dotnet/iot/tutorials/lcd-display
        }

    }
}
